﻿using System;
using System.IO;
using System.Text;

namespace CloudShot.Utils
{
  public static class DropboxUtils
  {
    private static string _dropboxFolder = null;

    public static string DropboxFolder
    {
      get
      {
        if (string.IsNullOrEmpty(_dropboxFolder))
          _dropboxFolder = GetDropboxFolder();

        return _dropboxFolder;
      }
    }

    public static string DropboxPublicFolder
    {
      get
      {
        if (!string.IsNullOrEmpty(DropboxFolder))
        {
          return Path.Combine(DropboxFolder, @"Public");
        }

        return string.Empty;
      }
    }

    private static string GetDropboxFolder()
    {
      string appData = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
      string hostDbPath = Path.Combine(appData, @"Dropbox\host.db");

      if (!File.Exists(hostDbPath))
        return string.Empty;

      using (FileStream fs = new FileStream(hostDbPath, FileMode.Open))
      {
        using (StreamReader reader = new StreamReader(fs))
        {
          var ignore = reader.ReadLine();
          string line = reader.ReadLine().Trim();
          byte[] data = Convert.FromBase64String(line);

          return Encoding.UTF8.GetString(data);
        }
      }
    }
  }
}
